package org.jetlinks.pro.things.utils;

import com.google.common.collect.Maps;
import org.jetlinks.core.message.ThingMessage;
import org.jetlinks.core.message.ThingMessageReply;
import org.jetlinks.core.message.function.ThingFunctionInvokeMessageReply;
import org.jetlinks.core.message.property.Property;
import org.jetlinks.core.message.property.PropertyMessage;
import org.jetlinks.pro.things.ThingConstants;

import java.util.Map;
import java.util.Set;

public class ThingsUtils {

    @SuppressWarnings("all")
    public static Map<String, Object> messageToContextMap(ThingMessage message) {
        Map<String, Object> map = Maps.newHashMapWithExpectedSize(32);

        if (message instanceof ThingMessageReply) {
            map.put("success", ((ThingMessageReply) message).isSuccess());
        }
        if (message instanceof ThingFunctionInvokeMessageReply) {
            Object output = ((ThingFunctionInvokeMessageReply) message).getOutput();
            if (output instanceof Map) {
                map.putAll(((Map) output));
            } else if (null != output) {
                map.put("__output", output);
            }
        } else if (message instanceof PropertyMessage) {
            PropertyMessage msg = ((PropertyMessage) message);
            for (Property property : msg.getCompleteProperties()) {
                map.put(property.getProperty(), property.getValue());
                map.put(property.getProperty() + ".timestamp", property.getTimestamp());
                map.put(property.getProperty() + ".state", property.getState());
            }
        }

        return map;
    }

    public static <T extends ThingMessage> T mergeHeader(ThingMessage from, T to) {

        from.getHeader(ThingConstants.connectorTrace)
            .ifPresent(traces -> {
                Set<String> traced = to.getOrAddHeaderDefault(ThingConstants.connectorTrace);
                if (traced != traces) {
                    traced.addAll(traces);
                }
            });

        return to;
    }
}
